"use client";
import { loginApi, registerApi, userInfoApi } from "@/api/login";
import Box from "@/components/Box";
import ButtonOwn from "@/components/ButtonOwn";
import MobileField from "@/components/Fields/MobileField";
import { Link, useRouter } from "@/i18n/routing";
import { useSystemStore } from "@/stores/useSystemStore";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { emailReg, neReg } from "@/utils";
import { setCookies } from "@/utils/Cookies";
import {
    Checkbox,
    DatePicker,
    DatePickerRef,
    Form,
    Input,
    Radio,
    Space,
    TextArea,
    Toast,
} from "antd-mobile";
import { PickerDate } from "antd-mobile/es/components/date-picker/util";
import clsx from "clsx";
import dayjs from "dayjs";
import { useTranslations } from "next-intl";
import { useSearchParams } from "next/navigation";
import { FC, RefObject, useRef, useState } from "react";
interface MobileFieldProps {
    value?: string;
    onChange?: (value: string) => void;
}

// const MobileField: FC<MobileFieldProps> = (props) => {
//     const t = useTranslations("form");
//     const { value, onChange } = props;
//
//     const changeHandler = (value: string) => {
//         let newAmount = value.replace(/[^0-9]/g, "");
//         if (onChange) {
//             onChange(newAmount);
//         }
//     };
//     return (
//         <>
//             <Space align="center" className={"text-[#ccc]"}>
//                 <Space align="center">+55</Space>
//                 <Input
//                     placeholder={t("phone")}
//                     maxLength={11}
//                     value={value}
//                     onChange={(e) => changeHandler(e)}
//                 />
//             </Space>
//         </>
//     );
// };

const SexMobile: FC<MobileFieldProps> = (props) => {
    const { value, onChange } = props;
    const handler = () => {
        console.log(`🚀🚀🚀🚀🚀-> in index.tsx on 58`, 123);
    };
    return (
        <div className={"w-[100%] border-4"} onClick={handler}>
            <Space align="center" className={"border-4 text-[#ccc]"}>
                <div className={"h-full w-[100%]"}>{value}</div>
            </Space>
        </div>
    );
};
interface FormProps {
    /**
     * 通讯地址
     */
    address?: string;
    /**
     * 用户头像
     */
    avatar_url?: string;
    /**
     * 生日：yyyy-MM-dd
     */
    birthday?: string;
    /**
     * 邮箱地址
     */
    email?: string;
    /**
     * 真实姓名
     */
    nick_name?: string;
    /**
     * 外部ID
     */
    open_id?: string;
    /**
     * 身份护照
     */
    passport?: string;
    /**
     * 用户密码
     */
    pwd: string;
    /**
     * 推荐码
     */
    referrer_code?: string;
    /**
     * 用户名
     */
    user_name?: string;
    /**
     * 用户电话号码
     */
    user_phone: string;
    /**
     * 用户类型
     */
    user_type?: string;
    sex?: number;
    /**
     * 渠道链接
     */
    channel_code?: string;

    code_phone?: string;
}
interface FormInitStateTypes extends FormProps {
    mobile?: {
        preValue: string;
        realValue: string;
    };
}
type FormType = "login" | "register";
interface Props {
    type?: FormType;
}
const FormComponent: FC<Props> = (props) => {
    const { type = "register" } = props;
    const isStrictMode = useSystemStore().identity_verify.register === 1;
    const { setUserInfo } = useUserInfoStore();
    const t = useTranslations();
    const searchParams = useSearchParams();
    const [statusText, setStatusText] = useState("");

    /// 密码可见
    const [visible, setVisible] = useState(false);
    const spanClassName = clsx("iconfont", {
        "icon-kejian": visible,
        "icon-bukejian": !visible,
    });
    // 是否同意协议
    const [checkBoxValue, setCheckBoxValue] = useState<boolean>(false);
    const router = useRouter();
    /// 初始值
    const params = useRef<FormInitStateTypes>({
        user_phone: "",
        mobile: { preValue: "55", realValue: "" },
        pwd: "",
        sex: 0,
        address: undefined,
        birthday: undefined,
        email: undefined,
        passport: undefined,
        referrer_code: undefined,
    });

    const onFinish = (values: FormInitStateTypes) => {
        const { mobile } = values;
        const newValue = {
            ...values,
            user_phone: `${mobile?.preValue}${mobile?.realValue}`,
            code_phone: mobile?.preValue,
        };

        delete newValue.mobile;
        if (isStrictMode) {
            strictHandler(newValue as FormProps);
        } else {
            looseHandler(newValue as FormProps);
        }
    };

    /// 严格模式
    const strictHandler = (values: FormProps) => {
        if (type !== "login") {
            if (!checkBoxValue) {
                Toast.show({
                    content: t("form.readyAgreement"),
                });
                return;
            }
            values.birthday = dayjs(values.birthday).format("YYYY/MM/DD");
        }

        looseHandler(values);
    };
    const loginHandler = async (values: FormProps) => {
        return new Promise(async (resolve, reject) => {
            const loginResult = await loginApi(values).catch((error) => {
                let text = error ? t(`code.${error.data.code}`) : t(`code.${500}`);
                Toast.show({
                    content: text,
                });
            });
            if (loginResult?.code === 200) {
                setCookies("Token", loginResult.data.token as string);
                const result = await userInfoApi();
                if (result.code === 200) {
                    setUserInfo(result.data);
                    resolve(result);
                    return result;
                }
            } else {
                reject();
            }
        });
    };
    /// 宽松模式
    const looseHandler = async (values: FormProps) => {
        // 请求
        Toast.show({
            icon: "loading",
            duration: 0,
        });
        // 注册
        if (type === "register") {
            const newValues = {
                ...values,
                referrer_code: sessionStorage.getItem("shareId") ?? undefined,
                channel_code: localStorage.getItem("channel_code") ?? undefined,

                //  轮盘邀请
                turntable_id: Number(sessionStorage.getItem("turntable_id")) ?? undefined,
                turntable_user_id: Number(sessionStorage.getItem("turntable_user_id")) ?? undefined,
                turntable_time: Number(sessionStorage.getItem("turntable_time")) ?? undefined,
            };
            registerApi(newValues)
                .then(async (res) => {
                    if (res.code === 200) {
                        loginHandler({
                            pwd: values.pwd,
                            user_phone: values.user_phone,
                            code_phone: values.code_phone,
                        }).then(() => {
                            router.replace("/recharge");
                            Toast.clear();
                        });
                    }
                })
                .catch((error) => {
                    if (error.data.code === 1017) {
                        sessionStorage.removeItem("shareId");
                    }

                    Toast.show({
                        content: t(`code.${error.data.code}`),
                    });
                });
        } else {
            /// 登录
            console.log(`🚀🚀🚀🚀🚀-> in index.tsx on 257`, values);
            loginHandler(values).then(() => {
                Toast.clear();
                const redirect = searchParams.get("redirect")
                    ? `/${searchParams.get("redirect")}`
                    : "/";
                router.replace(redirect);
            });
        }
    };

    const onConfirm = (value: PickerDate) => {
        const isChildren = dayjs().subtract(18, "year").isBefore(value);
        if (isChildren) {
            Toast.show({
                icon: "fail",
                content: t("form.NotSuitableForChildren"),
            });
        }
    };
    const ageValidator = (rule: any, value: PickerDate) => {
        const isChildren = dayjs().subtract(18, "year").isBefore(value);
        if (isChildren) {
            return Promise.reject(new Error(rule.message));
        } else {
            return Promise.resolve();
        }
    };

    // 手机号验证规则
    const checkMobile = (_: any, value: any) => {
        if (value.realValue.length < 10) {
            return Promise.reject(new Error(t("form.phoneMinReg")));
        } else {
            return Promise.resolve();
        }
    };
    return (
        <Box className={"custom-form"}>
            <Form
                style={{
                    "--border-bottom": "none",
                    "--border-top": "none",
                    "--border-inner": "none",
                }}
                initialValues={params.current}
                onFinish={onFinish}
                footer={
                    <ButtonOwn active>
                        {type === "login" ? t("form.loginText") : t("form.registerText")}
                    </ButtonOwn>
                }
            >
                <Form.Item name="mobile" rules={[{ required: true, validator: checkMobile }]}>
                    <MobileField />
                </Form.Item>

                <Form.Item
                    name="pwd"
                    label=""
                    extra={
                        <span className={spanClassName} onClick={() => setVisible(!visible)}></span>
                    }
                    rules={[
                        { required: true, message: t("form.passwordReg") },
                        { min: 6, max: 20, message: t("form.passwordMinReg") },
                    ]}
                >
                    <Input
                        placeholder={t("form.password")}
                        maxLength={20}
                        type={visible ? "text" : "password"}
                    />
                </Form.Item>

                {type !== "login" && isStrictMode ? (
                    <>
                        <Form.Item
                            name="user_name"
                            label=""
                            rules={[{ required: true, message: t("form.usernameReg") }]}
                        >
                            <Input placeholder={t("form.username")} />
                        </Form.Item>
                        <Form.Item
                            name="birthday"
                            clickable={false}
                            trigger={"onConfirm"}
                            arrowIcon={<i className={"iconfont icon-xiangyou1"}></i>}
                            onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                                datePickerRef.current?.open();
                            }}
                            rules={[
                                { required: true, message: t("form.birthdayReg") },
                                {
                                    message: t("form.NotSuitableForChildren"),
                                    validator: ageValidator,
                                },
                            ]}
                        >
                            <DatePicker
                                getContainer={null}
                                min={dayjs().subtract(50, "year").toDate()}
                                max={dayjs().toDate()}
                                style={{ background: "#fff", color: "#000" }}
                            >
                                {(value) =>
                                    value ? (
                                        dayjs(value).format("YYYY/MM/DD")
                                    ) : (
                                        <span className={"text-[#ccc]"}>{t("form.birthday")}</span>
                                    )
                                }
                            </DatePicker>
                        </Form.Item>

                        <Form.Item
                            name="email"
                            label=""
                            rules={[
                                { required: true, message: t("form.emailReg"), pattern: emailReg },
                            ]}
                        >
                            <Input placeholder={t("form.email")} />
                        </Form.Item>
                        <Form.Item name="sex">
                            <Radio.Group>
                                <Radio
                                    value={0}
                                    className={"mr-[0.1rem]"}
                                    style={{ "--icon-size": "18px" }}
                                >
                                    {t("form.sexMan")}
                                </Radio>
                                <Radio value={1} style={{ "--icon-size": "18px" }}>
                                    {t("form.sexWoman")}
                                </Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            name="passport"
                            label=""
                            rules={[{ required: true, message: t("form.cardReg"), pattern: neReg }]}
                        >
                            <Input placeholder={t("form.card")} maxLength={11} type={"text"} />
                        </Form.Item>

                        <Form.Item
                            name="address"
                            label=""
                            rules={[{ required: true, message: t("form.addressReg") }]}
                        >
                            <TextArea placeholder={t("form.address")} maxLength={40} />
                        </Form.Item>

                        <div className={"flex px-[0.1rem]"}>
                            <Checkbox
                                block
                                style={{ "--icon-size": "16px" }}
                                checked={checkBoxValue}
                                onChange={(value) => setCheckBoxValue(value)}
                            ></Checkbox>
                            <div className={"ml-[10px] select-none break-all text-[12px]"}>
                                {t("form.agreement")}
                                <Link href={"/preventLaunderMoney"} className={"text-[#1677ff]"}>
                                    {t("form.moneyAgreement")}
                                </Link>
                                、
                                <Link href={"/terms"} className={"text-[#1677ff]"}>
                                    {t("form.serverAgreement")}
                                </Link>
                                {t("form.agreementAnd")}
                                <Link href={"/gamingPolicy"} className={"text-[#1677ff]"}>
                                    {t("form.childrenAgreement")}
                                </Link>
                            </div>
                        </div>
                    </>
                ) : null}
            </Form>
            <div className="mb-[0.2rem] flex justify-between text-[0.12rem]">
                {type == "login" ? (
                    <>
                        <Link className={"text-[#fff]"} href="/resetPhone">
                            {t("LoginPage.forgetPwd")}
                        </Link>
                        <Link className={"text-[#fff]"} href="/register">
                            {t("LoginPage.registerGo")}
                        </Link>
                    </>
                ) : (
                    <Link className={"w-[100%] text-center text-[#fff]"} href="/login" replace>
                        {t("LoginPage.loginGo")}
                    </Link>
                )}
            </div>
        </Box>
    );
};

export default FormComponent;
